package com.supermarket.exception;

/**
 * 数据库操作异常类
 * 用于处理数据库连接和操作相关的异常
 */
public class DatabaseException extends Exception {
    private String operation;
    private int errorCode;

    public DatabaseException(String message) {
        super(message);
    }

    public DatabaseException(String message, Throwable cause) {
        super(message, cause);
    }

    public DatabaseException(String operation, String message, Throwable cause) {
        super(message, cause);
        this.operation = operation;
    }

    public DatabaseException(String operation, int errorCode, String message, Throwable cause) {
        super(message, cause);
        this.operation = operation;
        this.errorCode = errorCode;
    }

    public String getOperation() {
        return operation;
    }

    public int getErrorCode() {
        return errorCode;
    }

    /**
     * 获取用户友好的错误消息
     */
    public String getUserFriendlyMessage() {
        if (operation != null) {
            return String.format("执行 '%s' 操作时发生错误: %s", operation, getMessage());
        }
        return "数据库操作失败: " + getMessage();
    }

    /**
     * 判断是否为连接异常
     */
    public boolean isConnectionError() {
        return errorCode == 0 || 
               getMessage().contains("connection") || 
               getMessage().contains("timeout") ||
               getMessage().contains("Communications link failure");
    }

    /**
     * 判断是否为可重试的异常
     */
    public boolean isRetryable() {
        return isConnectionError() || 
               errorCode == 1205 || // Lock wait timeout
               errorCode == 1213;   // Deadlock
    }
}